package domein.models;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import domein.Peer;
import domein.PeerController;
import domein.PeerFile;

public class BestandenListModel extends AbstractTableModel implements Observer
{	
	private static final long serialVersionUID = 1L;
	private String[] columnNames = {"Filename", "Filesize", "IP-adres Peer"};
	private PeerController peerController;
	private Peer selectedPeer;
	private List<PeerFile> fileList = new ArrayList<PeerFile>();
	
	public BestandenListModel(PeerController peerController)
	{
		this.peerController = peerController;
		this.peerController.addObserver(this);
	}
	
	@Override
	public int getColumnCount() 
	{
		return columnNames.length;
	}

	@Override
	public int getRowCount() 
	{
		if(fileList != null) {
			return fileList.size();
		} else {
			return 0;
		}
	}
	
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) 
	{
		return fileList.get(rowIndex).toArrayList()[columnIndex];
	}
	
	public String getColumnName(int columnIndex)
	{
		return this.columnNames[columnIndex];
	}
	
	public PeerFile getPeerFileForIndex(int index)
	{
		PeerFile peerFile = fileList.get(index);
		return peerFile;
	}

	@Override
	public void update() 
	{
		if (selectedPeer != null) 
		{
			Peer peer = PeerController.getInstance().getPeer(selectedPeer.getIpAddress());
			
			if(peer != null) {
				this.fileList = PeerController.getInstance().getPeer(selectedPeer.getIpAddress()).getPeerFiles();
			} else {
				this.fileList = null;
			}
			
			fireTableDataChanged();
		}	
	}
	
	public void setSelectedPeer(Peer peer) {
		selectedPeer = peer;
		PeerController.getInstance().notifyObservers();
	}
	
	public Peer getSelectedPeer() {
		return selectedPeer;
	}
}
